# Windows主机统计数据收集脚本
# 用于收集物理机资源信息并写入JSON文件供Docker容器读取

param(
    [string]$OutputPath = ".\data\host_stats.json",
    [int]$IntervalSeconds = 60
)

function Get-HostStats {
    try {
        # 获取CPU信息
        $cpuPercent = (Get-Counter "\Processor(_Total)\% Processor Time").CounterSamples.CookedValue
        $cpuCount = (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors
        
        # 获取内存信息
        $os = Get-WmiObject -Class Win32_OperatingSystem
        $totalMemory = $os.TotalVisibleMemorySize * 1024
        $freeMemory = $os.FreePhysicalMemory * 1024
        $usedMemory = $totalMemory - $freeMemory
        $memoryPercent = [math]::Round(($usedMemory / $totalMemory) * 100, 2)
        
        # 获取磁盘信息
        $diskInfo = @{}
        Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 } | ForEach-Object {
            $total = $_.Size
            $free = $_.FreeSpace
            $used = $total - $free
            $percent = if ($total -gt 0) { [math]::Round(($used / $total) * 100, 2) } else { 0 }
            
            $diskInfo[$_.DeviceID] = @{
                total = $total
                used = $used
                free = $free
                percent = $percent
            }
        }
        
        # 获取网络信息
        $networkCounters = Get-Counter "\Network Interface(*)\Bytes Total/sec" -ErrorAction SilentlyContinue
        $totalBytesPerSec = ($networkCounters.CounterSamples | Where-Object { $_.InstanceName -ne "_Total" -and $_.InstanceName -notlike "*Loopback*" } | Measure-Object -Property CookedValue -Sum).Sum
        
        # 构建统计数据
        $stats = @{
            timestamp = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
            cpu = @{
                percent = [math]::Round($cpuPercent, 2)
                count = $cpuCount
                frequency = 0  # Windows下难以准确获取
                load_avg = @(0, 0, 0)  # Windows不支持
                source = "windows_host"
            }
            memory = @{
                total = $totalMemory
                used = $usedMemory
                available = $freeMemory
                percent = $memoryPercent
                source = "windows_host"
            }
            disk = $diskInfo
            network = @{
                bytes_sent = 0  # 需要更复杂的逻辑来分别统计
                bytes_recv = 0
                packets_sent = 0
                packets_recv = 0
                total_bytes_per_sec = $totalBytesPerSec
                source = "windows_host"
            }
            collection_time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }
        
        return $stats
    }
    catch {
        Write-Error "收集主机统计数据时出错: $_"
        return $null
    }
}

function Write-StatsToFile {
    param($Stats, $FilePath)
    
    try {
        # 确保目录存在
        $directory = Split-Path -Parent $FilePath
        if (-not (Test-Path $directory)) {
            New-Item -ItemType Directory -Path $directory -Force | Out-Null
        }
        
        # 写入JSON文件
        $jsonContent = $Stats | ConvertTo-Json -Depth 10 -Compress
        Set-Content -Path $FilePath -Value $jsonContent -Encoding UTF8
        
        Write-Host "$(Get-Date -Format 'HH:mm:ss') - 主机统计数据已更新: CPU $($Stats.cpu.percent)%, 内存 $($Stats.memory.percent)%"
    }
    catch {
        Write-Error "写入统计数据文件时出错: $_"
    }
}

# 主循环
Write-Host "开始收集Windows主机统计数据..."
Write-Host "输出文件: $OutputPath"
Write-Host "更新间隔: $IntervalSeconds 秒"
Write-Host "按 Ctrl+C 停止收集"

while ($true) {
    $stats = Get-HostStats
    if ($stats) {
        Write-StatsToFile -Stats $stats -FilePath $OutputPath
    }
    
    Start-Sleep -Seconds $IntervalSeconds
}